//
//  ItemDetailViewController.m
//  CS Inventory Manager
//
//  Created by Billy Zoellers on 2/28/13.
//  Copyright (c) 2013 Transylvania University. All rights reserved.
//

#import "ItemDetailViewController.h"
#import "EditItemDetailViewController.h"
#import "Item.h"
#import "CheckoutHistoryViewController.h"
#import "CheckoutRecordViewController.h"
#import "CheckoutHistoryNavigationViewController.h"
#import "PatronSelectionViewController.h"
#import "CheckInViewController.h"

@interface ItemDetailViewController ()

@end

@implementation ItemDetailViewController

@synthesize delegate;

- (void)setDetailItem:(id)newDetailItem
{
    // allow editing since we now have a detail item
    [self.navigationItem.rightBarButtonItem setEnabled:YES];
    
    if (_detailItem != newDetailItem) {
        _detailItem = newDetailItem;
        
        
        NSMutableString *title = [[NSMutableString alloc] init];
        [title appendString:[_detailItem model]];
        NSLog(@"Configure DVC for Item with name %@",[_detailItem model]);
        [self setTitle:title];
        
        // Update the view.
        [self.tableView reloadData];
        
        //Update check in/out button if needed
        if ([_detailItem isCheckedOut]) {
            self.checkOutButton.titleLabel.text = @"Check Item In";
        } else {
            self.checkOutButton.titleLabel.text = @"Check Item Out";
        }
    }
}

- (IBAction)checkoutButtonPress:(id)item {
    //Check to make sure an item is actually loaded, otherwise button should do nothing.
    if (_detailItem) {
        //Check to see if in check out or check in mode
        if ([self.detailItem isCheckedOut]) {
            //Call the check-in wizard
            [self performSegueWithIdentifier:@"CheckIn" sender:self.detailItem];
        } else {
            [self performSegueWithIdentifier:@"CheckOut" sender:self.detailItem];
        }
    }
}

- (IBAction)editModeButton:(id)sender {
    
    [self performSegueWithIdentifier:@"EditItem" sender:_detailItem];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

    if ([[segue identifier] isEqual: @"EditItem"]) {
        EditItemDetailViewController *nextController = segue.destinationViewController;
        nextController.theItem = sender;
        [nextController setDelegate:self];
        
    } else if ([[segue identifier] isEqual: @"CheckoutDetail"]) {
        CheckoutHistoryNavigationViewController *nextController = segue.destinationViewController;
        nextController.passThroughRecord = sender;
        [nextController setDelegate:self];
        
    } else if ([[segue identifier] isEqual: @"CheckoutHistory"]) {
        CheckoutHistoryNavigationViewController *nextController = segue.destinationViewController;
        nextController.passThroughItem = sender;
        [nextController setDelegate:self];
        
    } else if ([[segue identifier] isEqual: @"CheckOut"]) {
        PatronSelectionViewController *nextController = segue.destinationViewController;
        nextController.selectedItem = sender;
        nextController.cameFromDVC = YES;
    } else if ([[segue identifier] isEqual: @"CheckIn"]) {
        CheckInViewController *nextController = segue.destinationViewController;
        //Prepare for check-in wizard here
        nextController.item = sender;
    }
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // allow editing since we now have a detail item
    [self.navigationItem.rightBarButtonItem setEnabled:NO];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // if no item is selected
    if (!_detailItem) {
        return 1;
    }
    
    // asset information and asset status
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger rows = 0;
    
    // if no item is selected
    if (!_detailItem) {
        return 1;
    }
    
    // depends on the section
    switch (section) {
        case 0:
            // category, type, model, location, asset #, serial #
            rows = 10;
            break;
        case 1:
            // status and checkout history
            rows = 2;
            break;
    }
    
    return rows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellText;
    NSString *cellDetailText;
    NSString *CellIdentifier = @"itemDetailCell"; // standard type of cell to use
    UITableViewCell *cell;
    
    // might need to format some dates
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MM/dd/yyyy"];
    
    // depends on the section
    switch (indexPath.section) {
        case 0:
            // asset info section - depends on the row
            switch (indexPath.row) {
                case 0:
                    cellText = @"Category";
                    cellDetailText = [[[_detailItem myType] myCategory] name];
                    break;
                case 1:
                    cellText = @"Type";
                    cellDetailText = [[_detailItem myType] manufacturerAndName];
                    break;
                case 2:
                    cellText = @"Model";
                    cellDetailText = [_detailItem model];
                    break;
                case 3:
                    cellText = @"Location";
                    cellDetailText = [_detailItem location];
                    break;
                case 4:
                    cellText = @"Asset #";
                    cellDetailText = [_detailItem assetId];
                    break;
                case 5:
                    cellText = @"Serial #";
                    cellDetailText = [_detailItem serialNo];
                    break;
                case 6:
                    cellText = @"Cost";
                    cellDetailText = [NSString stringWithFormat:@"$%.02f",[_detailItem cost]];
                    break;
                case 7:
                    cellText = @"Value";
                    cellDetailText = [NSString stringWithFormat:@"$%.02f",[_detailItem itemValue]];
                    break;
                case 8:
                    cellText = @"Date Added";
                    cellDetailText = [dateFormat stringFromDate:[_detailItem dateAdded]];
                    break;
                case 9:
                    cellText = @"Notes";
                    cellDetailText = [_detailItem notes];
                    break;
                    
            }
            break;
        case 1:
            // status and checkout history section - depends on row
            switch (indexPath.row) {
                case 0:
                    cellText = @"Status";
                    if (![_detailItem checkoutActive]) {
                        // not checked out
                        if (![_detailItem status]) {
                            cellDetailText = @"New";
                        } else {
                            cellDetailText = [_detailItem status];
                        }
                        
                    } else {
                        // checked out
                        CellIdentifier = @"itemDetailCellDetailWithDisclosure";
                        if ([[[_detailItem checkoutActive] patrons] count] == 1) {
                            // single patron
                            cellDetailText = [NSString stringWithFormat:@"Checked out to %@",[[[[_detailItem checkoutActive] patrons] objectAtIndex:0] name]];
                            
                        } else {
                            // multiple patrons
                            cellDetailText = [NSString stringWithFormat:@"Checked out to Multiple Patrons"];
                            
                        }
                        
                    }
                    break;
                case 1:
                    CellIdentifier = @"itemDetailCellBasicWithDisclosure";
                    cellText = @"View Checkout History";
                    break;
            }
            break;
    }
    
    // if no item selected
    if (!_detailItem) {
        CellIdentifier = @"itemDetailCellBasic";
        
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        
        cell.textLabel.text = @"No item selected";
        return cell;
    }
    
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.textLabel.text = cellText;
    cell.detailTextLabel.text = cellDetailText;
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *title = nil;
    
    if (!_detailItem) {
        return title;
    }
    
    // depends on section
    switch (section) {
        // asset info
        case 0:
            title = @"Asset Information";
            break;
        // asset status
        case 1:
            title = @"Asset Status";
    }
    
    return title;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            // go directly to current checkout pop up
            if ([_detailItem checkoutActive]) {
                [self performSegueWithIdentifier:@"CheckoutDetail" sender:[_detailItem checkoutActive]];
            }
        } else {
            // go to checkout history pop up
            [self performSegueWithIdentifier:@"CheckoutHistory" sender:_detailItem];
        }
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
